package com.kushe.site.interceptor;

import com.kushe.dao.MessageDao;
import com.kushe.dao.NoticeDao;
import com.kushe.dao.UserDao;
import com.kushe.entity.User;
import com.kushe.util.SessionEnv;
import com.kushe.util.core.DaoFactory;
import com.kushe.util.tools.CookiesUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WhiteBlue on 15/4/4.
 */
public class GlobalInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ((CookiesUtil.getCookieObject("user", request) != null) && (request.getSession().getAttribute("user") == null)) {
            try {
                String cookies = (CookiesUtil.getCookieObject("user", request)).getValue();
                if (cookies.contains("-")) {
                    String split[] = cookies.split("-");
                    User user = DaoFactory.getDao(UserDao.class).getByCookies(split[0], split[1]);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                        request.getSession().setMaxInactiveInterval(3600 * 3);
                    } else {
                        CookiesUtil.removeCookie(response, "user");
                    }
                } else {
                    CookiesUtil.removeCookie(response, "user");
                }
            } catch (Exception e) {
                CookiesUtil.removeCookie(response, "user");
            }
        }

        if ((request.getSession().getAttribute("user") != null) && ((request.getSession().getAttribute("sessionEnv") == null))) {
            User user = (User) request.getSession().getAttribute("user");
            SessionEnv sessionEnv = new SessionEnv();
            NoticeDao noticeDao = DaoFactory.getDao(NoticeDao.class);
            MessageDao messageDao = DaoFactory.getDao(MessageDao.class);

            sessionEnv.setList_message(messageDao.listNew(user.getId()));
            sessionEnv.setList_notice(noticeDao.listMessageNew(user.getId()));
            sessionEnv.setList_order(noticeDao.listOrderNew(user.getId()));

            request.getSession().setAttribute("sessionEnv", sessionEnv);
            request.getSession().setMaxInactiveInterval(3600 * 1);

        }


        return true;
    }
}
